import axios from 'axios'
import router from '../router'
import {
    Message
} from 'element-ui'
import store from '../store'
import moment from 'moment'
axios.defaults.baseURL = '/'
axios.defaults.timeout = 30000
const toLogin = () => {
    Message.error('很抱歉，登录已过期，请重新登录')
    window.location.href = `${location.origin}/index.html#/login?redirect=${encodeURIComponent(window.location.href)}`
}
// 收集运行试验错误信息
const getExcuteMsg = (url, content) => {
    if (url.includes('/experiment/execution') && content) {
        let list = store.getters['common/getExcuteMegs']
        list.push({
            content,
            time: moment().format('YYYY-MM-DD HH:mm:ss')
        })
        store.commit('common/setExcuteMegs', list)
    }
}
axios.interceptors.request.use(config => {
    config.headers.Authentication = JSON.parse(localStorage.getItem('USER_TOKEN'))
    return config
}, error => {
    Message.error('加载超时')
    return Promise.reject(error)
})
axios.interceptors.response.use(data => {
    if (data.status === 200) {
        let {
            data: {
                errorCode,
                errorHint
            },
            request: {
                responseURL
            }
        } = data
        if (['PORTAL-10004', 'PORTAL-10007'].includes(errorCode)) {
            toLogin()
        } else {
            getExcuteMsg(responseURL, errorHint)
            return data
        }
    }
}, error => {
    router.push(`/${error.response.status}`)
    return Promise.reject(error)
})
export default axios
